import os
import tempfile

import pandas as pd
import requests
from qiniu import Auth

from ModelController import qiniuAPI


def getData(url):
    access_key, secret_key, bucket_name = qiniuAPI()
    q = Auth(access_key, secret_key)
    try:
        # 设置token过期时间，生成私有下载URL
        private_url = q.private_download_url(url, expires=86400)
        with tempfile.NamedTemporaryFile(delete=False) as temp_file:
            # 使用requests下载文件到临时文件
            response = requests.get(private_url)
            temp_file.write(response.content)
            temp_file.flush()  # 确保内容写入磁盘
            filename = temp_file.name  # 获取临时文件的完整路径

        with open(filename, 'rb') as downloaded_file:
            content = downloaded_file.read()
            if filename.endswith('.csv'):
                df = pd.read_csv(filename)
                df = pd.DataFrame(df)
            elif filename.endswith('.xlsx'):
                df = pd.read_excel(filename)
                df = pd.DataFrame(df)
            os.remove(filename)
            return df
    except requests.exceptions.RequestException as req_error:
        print(f"Network error occurred while downloading file: {req_error}")
        return "下载不下来哇"
